import React, { Component, Fragment } from "react";
import PropTypes from "prop-types";
import { Table } from "antd";

export default class CustomPagination extends Component {
    static propTypes = {
        api: PropTypes.func,
        pagination: PropTypes.object,
        columns: PropTypes.array,
        recDataSource: PropTypes.func,
        format: PropTypes.func,
    };
    static defaultProps = {
        api: () => {
            return new Promise((resolve, reject) => {
                resolve();
            });
        },
        pagination: {
            current: 1,
            pageSize: 10,
            total: 1,
        },
        columns: [],
        recDataSource: () => {},
        format: val => val,
    };
    constructor() {
        super();
        this.state = {
            pagination: {
                current: 1,
                pageSize: 10,
                total: 0,
                onChange: (current, pageSize) => {
                    this.setState({ pagination: { ...this.state.pagination, current, pageSize } }, () => this.getDataSource());
                },
            },
            columns: [],
            dataSource: [],
        };
    }
    UNSAFE_componentWillMount() {
        this.initComponent();
    }
    initComponent = () => {
        this.props.onRef ? this.props.onRef(this) : false;
        this.setState(
            {
                ...this.props,
                pagination: this.props.pagination === false ? false : { ...this.state.pagination, ...this.props.pagination },
            },
            () => {
                this.getDataSource();
            }
        );
    };
    getDataSource = () => {
        const { current, pageSize } = this.state;
        this.props.api({ current, pageSize }).then(res => {
            if (res.code === 200) {
                this.setState(
                    {
                        pagination: { ...this.state.pagination, total: res.total },
                        dataSource: this.props.format(res.data.map(item => ({ ...item, key: item._id }))),
                    },
                    () => this.props.recDataSource(this.state.dataSource)
                );
            }
        });
    };
    render() {
        const { pagination, columns, dataSource } = this.state;
        return (
            <Fragment>
                <Table
                    scroll={{
                        x: columns.reduce((pre, item) => {
                            return (pre.width ? pre.width : pre) + (item.width ? item.width : 0);
                        }),
                        y: 600,
                    }}
                    bordered
                    columns={columns}
                    dataSource={dataSource}
                    pagination={pagination}
                />
            </Fragment>
        );
    }
}
